package algorithm_demo.demo03;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 给定一棵二叉树的头节点head，和另外两个节点a和b。
 * 返回a和b的最低公共祖先
 *
 * @author Api
 * @date 2023/2/12 21:13
 */
public class Code07_LowestAncestor {
    private static class Node {
        int val;
        Node left;
        Node right;

        public Node(int val) {
            this.val = val;
        }
    }

    public static Node lowestAncestor1(Node head, Node o1, Node o2) {
        if (head == null) {
            return null;
        }
        //key的父节点是value
        Map<Node, Node> parentMap = new HashMap<>();
        parentMap.put(head, null);
        fillParentMap(head, parentMap);
        Set<Node> o1Set = new HashSet<>();
        Node cur = o1;
        o1Set.add(cur);
        while (parentMap.get(cur) != null) {
            cur = parentMap.get(cur);
            o1Set.add(cur);
        }
        cur = o2;
        while (!o1Set.contains(cur)) {
            cur = parentMap.get(cur);
        }
        return cur;
    }


    public static void fillParentMap(Node head, Map<Node, Node> parentMap) {
        if (head.left != null) {
            parentMap.put(head.left, head);
            fillParentMap(head.left, parentMap);
        }
        if (head.right != null) {
            parentMap.put(head.right, head);
            fillParentMap(head.right, parentMap);
        }
    }

    //1. o1和o2没有一个在X节点上
    //2. o1和o2只有一个在X上
    //3. o1和o2都在X为头的树上
    // 3.1 左树和右树各一个
    // 3.2 左树包含o1和o2
    // 3.3 右树包含o1和o2
    // 3.4 X自己是o1或者o2
    public static Node lowestAncestor2(Node head, Node o1, Node o2) {
        return process(head, o1, o2).ans;
    }


    public static Info process(Node x, Node o1, Node o2) {
        if (x == null) {
            return new Info(null, false, false);
        }
        Info leftInfo = process(x.left, o1, o2);
        Info rightInfo = process(x.right, o1, o2);
        //是否发现o1和o2
        boolean findO1 = x == o1 || leftInfo.findO1 || rightInfo.findO1;
        boolean findO2 = x == o2 || leftInfo.findO2 || rightInfo.findO2;
        //o1和o2最初的交汇点在哪里？
        Node ans = null;
        //在左树上已经提前交汇了
        if (leftInfo.ans != null){
            ans = leftInfo.ans;
        }
        //在右树上已经提前交汇了
        if (rightInfo.ans != null){
            ans = rightInfo.ans;
        }
        //如果左树和右树都没有找到,并且O1和O2有找到了，则X为交汇点
        if (ans == null){
            if (findO1 && findO2){
                ans = x;
            }
        }
        return new Info(ans, findO1, findO2);
    }

    public static class Info {
        public Node ans;
        public boolean findO1;
        public boolean findO2;

        public Info(Node ans, boolean findO1, boolean findO2) {
            this.ans = ans;
            this.findO1 = findO1;
            this.findO2 = findO2;
        }
    }
}
